package com.ljpz.manage.service;

import com.ljpz.manage.pojo.ContentCategory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liujunchen on 2016/12/9.
 */
@Service
public class ContentCategoryService extends  BaseService<ContentCategory> {
    public void saveContentCategory(ContentCategory contentCategory) {
            contentCategory.setIsParent(false);
            contentCategory.setId(null);
            contentCategory.setStatus(1);
            contentCategory.setSortOrder(1);
            super.save(contentCategory)  ;
            ContentCategory contentCategory1 =   super.queryById(contentCategory.getParentId());
            if (!contentCategory1.getIsParent()){
                contentCategory1.setIsParent(true);
                super.update(contentCategory1) ;
            }
    }

    public void deleteAll(ContentCategory contentCategory) {
         List<Object> ids=  new ArrayList<Object>()  ;
         ids.add(contentCategory.getId())   ;
        //查询contenCategory下面所有的子节点
        this.findAllSubNode(ids,contentCategory.getId());
        //用递归算法算出后批量提交删除
        super.deleteByIds(ids , ContentCategory.class,"id");
        //判断该节点是否还有兄弟节点，如果没有修改父节点的isParent为false
        ContentCategory record =  new ContentCategory();
        record.setParentId(contentCategory.getParentId());
        List<ContentCategory>list=   super.queryListByWhere(record) ;
        if (null==list||list.isEmpty())
        {
            ContentCategory parent = new ContentCategory();
            parent.setId(contentCategory.getParentId());
            parent.setIsParent(false);
            super.updateSelective(parent) ;
        }
        }
        private   void   findAllSubNode(List<Object>ids  , Long pid ){
            ContentCategory  contentCategory = new ContentCategory()  ;
            contentCategory.setParentId(pid);
            List<ContentCategory> contentCategoryList =   super.queryListByWhere(contentCategory)  ;
            for (ContentCategory contentCategory1 :contentCategoryList){
                 ids.add(contentCategory1.getId());
             //循环添加要删除的名单
                if (contentCategory1.getIsParent())
                    //采用递归的方法遍历到数组ids中区
                {
                    findAllSubNode(ids,contentCategory1.getId()) ;
                }
            }
        }

    }

